import { useAntdTable } from 'ahooks';
import type { TableProps } from 'antd';
import { Form, Input, Select, Space, Table } from 'antd';
import { useEffect, useRef, useState } from 'react';

import rolesApi from '@/api/rolesApi';
import userApi from '@/api/usersApi';
import { message, modal } from '@/components/AntdGlobal';
import AuthButton from '@/components/AuthButton';
import SearchForm from '@/components/SearchForm';
import { IRole, IUser } from '@/types/api';
import { IAction } from '@/types/modal';
import { formatDate, formatState } from '@/utils';

import CreateUser from './createUser';

const UserList = () => {
    /* 数据管理--------------------------------------------------- */
    const [form] = Form.useForm();
    const [allRoleList, setAllRoleList] = useState<IRole.RoleItem[]>([]);
    const [userIds, setUserIds] = useState<string[]>([]);
    const userRef = useRef<{
        openModal: (action: IAction, data?: IUser.UserItem) => void;
    }>();
    const columns: TableProps<IUser.UserItem>['columns'] = [
        {
            title: '用户ID',
            dataIndex: 'userId',
            key: 'userId'
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
            key: 'userName'
        },
        {
            title: '用户邮箱',
            dataIndex: 'userEmail',
            key: 'userEmail'
        },
        {
            title: '用户角色',
            dataIndex: 'roleList',
            key: 'roleList',
            render(roleList: string[]) {
                return (
                    <Space>
                        {roleList.map((roleId: string) => {
                            return (
                                <span key={roleId}>
                                    {allRoleList.find((role) => role.roleId === roleId)?.roleName || ''}
                                </span>
                            );
                        })}
                    </Space>
                );
            }
        },
        {
            title: '用户状态',
            dataIndex: 'state',
            key: 'state',
            render(state: string) {
                return formatState(state);
            }
        },
        {
            title: '注册时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render(createTime: string) {
                return formatDate(createTime);
            }
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render(_, record: IUser.UserItem) {
                return (
                    <Space>
                        <Space>
                            <AuthButton
                                auth="user@edit"
                                type="text"
                                onClick={() => handleEdit(record)}
                            >
                                编辑
                            </AuthButton>
                            <AuthButton
                                auth="user@delete"
                                type="text"
                                danger
                                onClick={() => handleSingleDel(record.userId)}
                            >
                                删除
                            </AuthButton>
                        </Space>
                    </Space>
                );
            }
        }
    ];
    const getTableData = (
        {
            current,
            pageSize
        }: {
            current: number;
            pageSize: number;
        },
        formData: IUser.SearchParams
    ) => {
        return userApi
            .getUsersList({
                ...formData,
                pageNum: current,
                pageSize
            })
            .then((res) => {
                const { data } = res;
                return {
                    total: data.page.total,
                    list: data.list
                };
            });
    };
    const { tableProps, search } = useAntdTable(getTableData, {
        form,
        defaultParams: [
            { current: 1, pageSize: 10 },
            // 默认查询条件,优先级高于SearchForm的props.initialValues设置
            { state: '1' }
        ]
    });

    /* hooks ---------------------------------------------------- */
    useEffect(() => {
        getAllRoleList();
    }, []);

    /* 函数定义 ---------------------------------------------------*/
    /**获取角色列表
     */
    const getAllRoleList = async () => {
        const { data } = await rolesApi.getAllRoleList();
        setAllRoleList(data);
    };

    /**创建用户
     * @param userId
     */
    const handleCreate = () => {
        userRef.current?.openModal('create');
    };

    /**编辑用户
     * @param record 当前行数据
     */
    const handleEdit = (record: IUser.UserItem) => {
        userRef.current?.openModal('edit', record);
    };

    /**删除选中用户
     * @param userId
     */
    const handleSingleDel = (userId: string) => {
        modal.confirm({
            title: '删除确认',
            content: <span>确认删除该用户吗?</span>,
            onOk: () => {
                handleExecuteDel([userId]);
            }
        });
    };

    /**批量删除用户
     * @returns
     */
    const handleBatchDel = () => {
        if (userIds.length === 0) {
            message.error('请选择要删除的用户');
            return;
        }

        modal.confirm({
            title: '删除确认',
            content: <span>确认删除该批用户吗？</span>,
            onOk: () => {
                handleExecuteDel(userIds);
            }
        });
    };

    /**执行删除用户
     * @param ids
     */
    const handleExecuteDel = async (userIds: string[]) => {
        await userApi.delUser({
            userIds
        });
        message.success('删除成功');
        setUserIds([]);
        search.reset();
    };

    /**table选中行
     * @param newSelectedRowKeys 用户id列表
     */
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setUserIds(newSelectedRowKeys as string[]);
    };

    /**初始化更新用户列表
     */
    const updateUsersList = () => {
        search.reset();
    };

    return (
        <div className="user-list">
            {/* 表单 */}
            <SearchForm
                form={form}
                submit={search.submit}
                reset={search.reset}
            >
                <Form.Item
                    name="userId"
                    label="用户ID"
                >
                    <Input placeholder="请输入用户ID" />
                </Form.Item>
                <Form.Item
                    name="userName"
                    label="用户名称"
                >
                    <Input placeholder="请输入用户名称" />
                </Form.Item>
                <Form.Item
                    name="state"
                    label="状态"
                >
                    <Select style={{ width: 120 }}>
                        <Select.Option value="0">所有</Select.Option>
                        <Select.Option value="1">在职</Select.Option>
                        <Select.Option value="2">离职</Select.Option>
                        <Select.Option value="3">试用期</Select.Option>
                    </Select>
                </Form.Item>
            </SearchForm>

            {/* table */}
            <div className="base-table">
                <div className="header-wrapper">
                    <div className="title">用户列表</div>
                    <div className="action">
                        <Space>
                            <AuthButton
                                auth="user@create"
                                type="primary"
                                onClick={handleCreate}
                            >
                                新增
                            </AuthButton>
                            <AuthButton
                                auth="user@delete"
                                type="primary"
                                danger
                                onClick={handleBatchDel}
                            >
                                批量删除
                            </AuthButton>
                        </Space>
                    </div>
                </div>
                <Table
                    bordered
                    rowKey="userId"
                    rowSelection={{
                        type: 'checkbox',
                        // selectedRowKeys使之变为受控组件，避免刷新后依然选中
                        selectedRowKeys: userIds,
                        onChange: onSelectChange
                    }}
                    columns={columns}
                    {...tableProps}
                />
            </div>

            {/* 操作弹框 */}
            <CreateUser
                mRef={userRef}
                update={updateUsersList}
            />
        </div>
    );
};

export default UserList;
